import React,{Fragment} from "react";
import styles from './login.module.css';
import {Form, Input, Icon, Button,Row,Col,Message} from 'antd';
import {Captcha,Login} from "../../api/AccountApi";
import {
    setCaptchaToken,
    getCaptchaToken,
    login
} from "../../libs/storage"
import {jump} from '../../libs/funcs'

/**
 * 密码方式登录
 */
@Form.create()
class PasswordMethod extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            base64_img:props.isLogin ? "" : this.getCaptcha(),
            loading:false
        }
    }

    // 获取验证码
    getCaptcha = () => {
        Captcha().then(response => {
            // 存储验证码token
            setCaptchaToken(response.headers.authorization);
            // 转换为base64图片
            let base64_img = 'data:image/png;base64,' + btoa(
                new Uint8Array(response.data)
                    .reduce((data,byte) => data + String.fromCharCode(byte),'')
            );
            this.setState({
                base64_img
            })
        }).catch(error => {
            Message.error("获取验证码错误",1)
        })
    };

    handleSubmit = () => {
        this.props.form.validateFields((err, formData) => {
            if (!err) {
                formData["token"] = getCaptchaToken();
                this.setState({loading:true})
                Login(formData).then(response => {
                    if(response.data.code === 200){
                        let userInfo = response.data.user_info;
                        console.log("userInfo",userInfo)
                        userInfo["pic"] = userInfo.pic && userInfo.pic.length > 0 && userInfo.pic[0].hasOwnProperty("thumbUrl") ? userInfo.pic[0]["thumbUrl"] : "";
                        // 登录成功
                        login(response.data.access_token,response.data.user_info);
                        jump();
                        Message.success("登录成功",1);
                    }else {
                        this.getCaptcha();
                    }
                }).catch(error => {
                    console.log(error)
                }).finally(() => {this.setState({loading:false})})
            }else {
                this.getCaptcha();
            }
        })
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Fragment>
                <Form>
                    <Form.Item className={styles.formItem}>
                        {getFieldDecorator('username', {rules: [{required: true, message: '请输入用户名'}]})(
                            <Input
                                size="large"
                                autoComplete="off"
                                placeholder="请输入用户名"
                                prefix={<Icon type="user" className={styles.icon}/>}/>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem}>
                        {getFieldDecorator('password', {rules: [{required: true, message: '请输入密码'}]})(
                            <Input
                                size="large"
                                type="password"
                                autoComplete="off"
                                placeholder="请输入密码"
                                onPressEnter={this.handleSubmit}
                                prefix={<Icon type="lock" className={styles.icon}/>}/>
                        )}
                    </Form.Item>
                    <Form.Item className={styles.formItem}>
                        {getFieldDecorator('code', {rules: [{required: true, message: '请输入验证码'}]})(
                                <Row gutter={13}>
                                    <Col span={15}>
                                        <Input
                                            size="large"
                                            autoComplete="off"
                                            placeholder="请输入验证码"
                                            onPressEnter={this.handleSubmit}
                                            prefix={<Icon type="lock" className={styles.icon}/>}/>
                                    </Col>
                                    <Col span={9}>
                                        <span><img onClick={this.getCaptcha}  src={this.state.base64_img} alt=""/></span>
                                    </Col>
                                </Row>
                            )
                        }
                    </Form.Item>

                </Form>
                <Button
                  block
                  size="large"
                  type="primary"
                  className={styles.button}
                  loading={this.state.loading}
                  onClick={this.handleSubmit}>登录</Button>
            </Fragment>
        );
    }
}

export default PasswordMethod;
